package thread;

/**
 * 有效的缩小同步范围可以在保证并发安全的前提下提高并发效率
 */
public class SyncDemo2 {
    public static void main(String[] args) {
//        Shop shop = new Shop();
        Shop shop1 = new Shop();
        Shop shop2 = new Shop();
        Thread t1 = new Thread("范传奇"){
            public void run(){
//                shop.buy();
                shop1.buy();
            }
        };
        Thread t2 = new Thread("王克晶"){
            public void run(){
//                shop.buy();
                shop2.buy();
            }
        };
        t1.start();
        t2.start();
    }
}

class Shop{
//    在方法上使用synchronized时，锁对象不可选，只能是this
//    public synchronized void buy(){
    public void buy(){
        try {
            Thread t = Thread.currentThread();//获取运行该方法的线程
            System.out.println(t.getName()+":正在挑衣服...");
            Thread.sleep(5000);
            //同步监视器对象通常使用临界资源即可(多个线程抢谁就锁谁)
//            synchronized ("123") {
            synchronized (this) {
                System.out.println(t.getName() + "正在试衣服...");
                Thread.sleep(5000);
            }

            System.out.println(t.getName()+"结账离开");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}








